package web.util;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.AbstractLobCreatingPreparedStatementCallback;
import org.springframework.jdbc.support.lob.DefaultLobHandler;
import org.springframework.jdbc.support.lob.LobCreator;
import org.springframework.jdbc.support.lob.LobHandler;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * 大字段处理方式
 */
public class LobOperator {

    public static void saveLob(JdbcTemplate jdbcTemplate, String sql, final int id, final byte[] content) {

        final LobHandler lobHandler = new DefaultLobHandler();
        jdbcTemplate.execute(sql, new AbstractLobCreatingPreparedStatementCallback(lobHandler) {
            protected void setValues(PreparedStatement ps,
                                     LobCreator lobCreator) throws SQLException,
                    DataAccessException {
                ps.setInt(2, id);
                lobCreator.setBlobAsBytes(ps, 1, content);
            }
        });
    }

    public static byte[] getLob(JdbcTemplate jdbcTemplate, String sql, Object[] params) {
        final LobHandler lobHandler = new DefaultLobHandler();
        List<byte[]> result = (List<byte[]>) jdbcTemplate.query(
                sql, params,
                new RowMapper() {
                    public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
                        byte[] result = lobHandler.getBlobAsBytes(rs, 1);
                        return result;
                    }
                });
        if (null != result && !result.isEmpty()) {
            return result.get(0);
        }
        return null;
    }
}
